﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace GameServer.Tools
{
    public class Configuration
    {
        private string config;
        private Dictionary<String, String> values = new Dictionary<String, String>();

        public Configuration(string fileName)
        {
            this.config = fileName;
        }

        public void Load()
        {
            if (!LoadConfig())
            {
                throw new Exceptions.EmptyServerPropertiesException(config + " has no properties.");
            }
        }

        private bool LoadConfig()
        {
            try
            {
                StreamReader sr = new StreamReader(config);
                int LineLoc = 0;
                while (!sr.EndOfStream)
                {
                    string x = sr.ReadLine();
                    LineLoc++;
                    string[] confval = x.Split('=');

                    if (confval.Length == 2)
                    {
                        values.Add(confval[0].Trim(), confval[1].Trim());
                    }
                    else
                    {
                        Logger.Log(LevelType.INFO, "There is an unknown line in your " + config + " file, line " + LineLoc + ".");
                    }
                }

                sr.Close();
                
                return (values.Count > 0);
            }
            catch (FileNotFoundException e)
            {
                throw new Exceptions.EmptyServerPropertiesException(config + " does not exist.");
            }
        }

        public string getString(string key)
        {
            string retval = null;
            values.TryGetValue(key, out retval);
            return retval;
        }

        public int getInt(string key)
        {
            string retval = "-1";
            values.TryGetValue(key, out retval);
            return int.Parse(retval);
        }
    }
}
